import React from 'react';
import { withRouter } from 'umi';
import { Spin, Form, Result } from 'antd';
import moment from 'moment';
import { Toast } from 'antd-mobile';
import { useRequest, defaultFormatResult } from '@/hooks';
import { dictionaryList } from '@/services/dictionary';
import { primaryColor } from '@/defaultSettings';
import { PageWrap, Header, Tips, Button, PersonInfo, ListItem, DeclareInfo } from './components';
import { getRegisterDetail, getDeclare, updateRegisterStatus } from '../service';
import { pushRoute } from '../utils';
import styles from './Register.less';

import add from '../images/icon-add.png';

const AddButton = ({ ...rest }) => (
    <ListItem
        title={
            <div
                style={{
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    color: primaryColor,
                    fontSize: 16
                }}
            >
                <img alt="" src={add} width="20" height="20" style={{ marginRight: 4 }} />
                添加
            </div>
        }
        showArrow={false}
        {...rest}
    />
);

const titleStyle = { fontSize: 14, lineHeight: '22px', color: '#2A2F3C' };
const subTitleStyle = { fontSize: 14, color: '#BCC1CD', wordBreak: 'break-all' };

const formatDate = (startTime, endTime) => {
    const st = (startTime && moment(startTime).format('YYYY.MM')) || '';
    const et = (endTime && moment(endTime).format('YYYY.MM')) || '至今';
    return `${st}-${et}`;
};

const ItemHead = ({ title, extra }) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', paddingRight: 3 }}>
        <div style={{ flex: 1, ...titleStyle }}>{title}</div>
        <div style={{ ...titleStyle, fontSize: 12, marginLeft: 24 }}>{extra}</div>
    </div>
);

const getDictName = (arr, value) => {
    if (arr && arr.length > 0) {
        return arr.find(item => item.dictValue === value)?.dictName || '';
    }
    return '';
};

const PERSON_INFO_CHECK_KEY = [
    'talentName',
    'talentSex',
    'phoneAreaCode',
    'talentEmail',
    'talentBirth',
    'lastPostStatus'
];
const EDU_CHECK_KEY = ['startTime', 'endTime', 'graduateSchool', 'major', 'degree', 'academicYear'];

const Register = ({ form, location }) => {
    const { query } = location;

    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [done, setDone] = React.useState(false);

    // 获取声明信息
    const { data: declareDetail } = useRequest(() => getDeclare(query?.nid), {
        ...defaultFormatResult
    });

    // 获取表单字典
    const { data: dictObj } = useRequest(
        () =>
            dictionaryList({
                codes: ['agreeType']
            }),
        {
            formatResult: res => {
                if (res) {
                    const { code, data, msg } = res;
                    if (code === 10000) {
                        const obj = {};
                        data.forEach(item => {
                            if (obj[item.code]) {
                                obj[item.code].push(item);
                            } else {
                                obj[item.code] = [item];
                            }
                        });
                        return obj;
                    }
                    Toast.info(msg);
                }
                return undefined;
            }
        }
    );
    console.log('getRegisterDetail---------Register');
    const { loading, data: resumeDetail } = useRequest(() => getRegisterDetail(query?.nid), {
        ...defaultFormatResult
    });

    const talentEduDetailVOList = resumeDetail?.talentEduDetailVOList || [];

    const handleSubmit = () => {
        // eslint-disable-next-line no-restricted-syntax
        for (const key of PERSON_INFO_CHECK_KEY) {
            if (!resumeDetail[key]) {
                Toast.info('请完善个人信息');
                return;
            }
        }

        if (talentEduDetailVOList.length === 0) {
            Toast.info('请填写教育背景');
            return;
        }

        // eslint-disable-next-line no-restricted-syntax
        for (const eduValue of talentEduDetailVOList) {
            // eslint-disable-next-line no-restricted-syntax
            for (const key of EDU_CHECK_KEY) {
                if (!eduValue[key]) {
                    Toast.info('请完善教育背景');
                    return;
                }
            }
        }
        if (!resumeDetail.expectSalary) {
            Toast.info('请填写薪资意向');
            return;
        }
        if (declareDetail?.settingSwitch === 1 && !form.getFieldValue('remove')) {
            Toast.info('提交应聘登记表需勾选同意声明');
            return;
        }
        form.validateFields(async err => {
            if (!err) {
                setSubmitLoading(true);
                const finalParams = {
                    resumeId: resumeDetail?.resumeId,
                    registerStatusFlag: 1
                };
                setSubmitLoading(true);
                updateRegisterStatus(finalParams)
                    .then(res => {
                        const { code, msg } = res;
                        if (code === 10000) {
                            setDone(true);
                        } else {
                            Toast.info(msg);
                        }
                    })
                    .finally(() => {
                        setSubmitLoading(false);
                    });
            } else {
                const tempList = Object.values(err);
                if (tempList && tempList.length > 0) {
                    const { errors } = tempList[0];
                    Toast.info(errors[0]?.message);
                }
            }
        });
    };

    const handleRoute = (path, flag) => {
        if (flag) {
            return;
        }
        pushRoute(path);
    };

    if (done) {
        return (
            <div className={styles.interviewMobile} style={{ background: '#fff' }}>
                <Result status="success" title="提交成功！" />
            </div>
        );
    }

    return (
        <PageWrap
            footer={
                <Button type="primary" loading={submitLoading} onClick={handleSubmit}>
                    提交
                </Button>
            }
        >
            <Spin spinning={loading}>
                <div style={{ background: '#fff' }}>
                    <Header />
                    <Tips
                        title="《应聘登记表》信息为简历自动解析的结果，请确认并完善相关信息"
                        style={{ paddingTop: 8 }}
                    />
                    <div style={{ padding: '0 16px 16px' }}>
                        <PersonInfo
                            data={resumeDetail}
                            onClick={() =>
                                pushRoute({
                                    pathname: '/recruitment/register/info',
                                    query
                                })
                            }
                        />
                        <ListItem
                            title="教育背景"
                            showArrow={!(talentEduDetailVOList?.length > 0)}
                            extra="待填写"
                            onClick={() =>
                                handleRoute(
                                    {
                                        pathname: '/recruitment/register/education',
                                        query: {
                                            id: query?.id,
                                            talentCode: resumeDetail?.talentCode
                                        }
                                    },
                                    talentEduDetailVOList?.length > 0
                                )
                            }
                            titleStyle={{
                                paddingBottom: talentEduDetailVOList?.length > 0 ? 8 : 16
                            }}
                            contentStyle={{ paddingBottom: 0 }}
                        >
                            {talentEduDetailVOList?.length > 0 &&
                                talentEduDetailVOList.map(item => (
                                    <ListItem
                                        key={item.id}
                                        bordered={false}
                                        style={{
                                            paddingLeft: 0,
                                            paddingRight: 0
                                        }}
                                        title={
                                            <ItemHead
                                                title={item.graduateSchool}
                                                extra={formatDate(item.startTime, item.endTime)}
                                            />
                                        }
                                        titleStyle={{
                                            paddingTop: 4,
                                            paddingBottom: 4
                                        }}
                                        iconStyle={{
                                            top: 10,
                                            transform: 'none'
                                        }}
                                        onClick={() =>
                                            handleRoute({
                                                pathname: '/recruitment/register/education',
                                                query: { id: query?.id, nid: item.id }
                                            })
                                        }
                                    >
                                        <div style={subTitleStyle}>
                                            {getDictName(dictObj?.agreeType, item.degree)} · {item.major}
                                        </div>
                                    </ListItem>
                                ))}
                        </ListItem>
                        {talentEduDetailVOList?.length > 0 && (
                            <AddButton
                                onClick={() =>
                                    handleRoute({
                                        pathname: '/recruitment/register/education',
                                        query: { id: query?.id, talentCode: resumeDetail?.talentCode }
                                    })
                                }
                            />
                        )}
                        <ListItem
                            title="薪资意向"
                            onClick={() =>
                                pushRoute({
                                    pathname: '/recruitment/register/intension',
                                    query
                                })
                            }
                            contentStyle={{
                                paddingBottom:
                                    (resumeDetail?.currentMonthSalary && resumeDetail?.monthCount) ||
                                    resumeDetail?.expectSalary
                                        ? 16
                                        : 0
                            }}
                            showArrow
                            extra={resumeDetail?.expectSalary ? '' : '待填写'}
                        >
                            {resumeDetail?.expectSalary && (
                                <div>
                                    期望年薪{' '}
                                    {resumeDetail?.expectSalary
                                        ? Number(resumeDetail?.expectSalary).toLocaleString('en-US')
                                        : ''}{' '}
                                    {resumeDetail?.expectSalaryCurrencyCode || resumeDetail?.companyCurrencyCode}
                                </div>
                            )}
                            {resumeDetail?.expectSalary && resumeDetail?.expectMonthNumber && (
                                <div style={{ color: '#BCC1CD', marginTop: 5 }}>
                                    {Number(
                                        (resumeDetail?.expectSalary / resumeDetail?.expectMonthNumber).toFixed(0)
                                    ).toLocaleString('en-US')}{' '}
                                    {' X '}
                                    {resumeDetail?.expectMonthNumber}{' '}
                                    {resumeDetail?.expectSalaryCurrencyCode || resumeDetail?.companyCurrencyCode}
                                </div>
                            )}
                        </ListItem>
                    </div>
                    {declareDetail?.settingSwitch === 1 && (
                        <div className={styles.declare}>
                            <DeclareInfo
                                isMobile
                                form={form}
                                id={query?.id}
                                title={declareDetail?.statementContent}
                                file={declareDetail?.clause}
                            />
                        </div>
                    )}
                </div>
            </Spin>
        </PageWrap>
    );
};

export default withRouter(Form.create({})(Register));
